package com.shushan.manager;

import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.common.ui.OnRecyclerviewItemClickListener;
import com.android.xrecyclerview.ProgressStyle;
import com.android.xrecyclerview.XRecyclerView;
import com.shushan.base.BaseFragment;
import com.shushan.lockscreen.GamesFloatWindow;
import com.shushan.lockscreen.bean.AppInfo;
import com.shushan.manager.adapter.SoftMgPagerAdapter;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.util.ControlUtil;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToastUtils;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;

import java.util.List;

/**
 * @ClassName: SoftWareMgFragment
 * @Desciption: 软件管理fragement
 * @author: yichaohua
 * @date: 2018-07-17
 */
public class SoftWareMgFragment extends BaseFragment implements XRecyclerView.LoadingListener{

    private static final String TAG = "SoftWareMgFragment";

    private int type;//软件管理类型;1:全部软件 2:黑名单 3:白名单

    private XRecyclerView recyclerView;
    private SoftWareAdapter softWareAdapter;

    private boolean isLoaded = false;
    private int mTabPos = 0;
    private boolean isFirst = true;

    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            Log.i(TAG, "isLoaded=" + isLoaded);
            if(!isLoaded){
                isLoaded = true;
                //这里执行加载数据的操作
                Log.i(TAG, "page="+(mTabPos+1));

                recyclerView.refresh();
            }
            return;
        };
    };

    public SoftWareMgFragment() {
    }

    @SuppressLint("ValidFragment")
    public SoftWareMgFragment(int type) {
        this.type = type;
        this.mTabPos = (type - 1);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.soft_mg_fragment, null);
        initView(view);

        //设置页和当前页一致时加载，防止预加载
        if (isFirst && mTabPos == 0) {
            isFirst = false;
            sendMessage();
        }

        return view;
    }

    private void initView(View view) {
        recyclerView = view.findViewById(R.id.soft_mg_rv);
        //设置RecyclerView 布局
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        recyclerView.setArrowImageView(R.drawable.refresh_down_arrow);
        recyclerView.getDefaultRefreshHeaderView().setRefreshTimeVisible(true);
        recyclerView.setLoadingMoreEnabled(false);
        recyclerView.setLoadingListener(this);

        softWareAdapter = new SoftWareAdapter();
        recyclerView.setAdapter(softWareAdapter);
    }

    @Override
    public void onRefresh() {
        new GetAppListTask().execute();
    }

    @Override
    public void onLoadMore() {

    }


    private class GetAppListTask extends AsyncTask<Void,Void,List<AppInfo>> {

        @Override
        protected List<AppInfo> doInBackground(Void... voids) {
            if(type == 2){
                return SystemUtils.getUsePackages(false,getActivity());
            }else if(type == 3){
                return SystemUtils.getUsePackages(true,getActivity());
            }else {
                return SystemUtils.getUsePackages(getActivity());
            }

        }

        @Override
        protected void onPostExecute(List<AppInfo> appInfoList) {
            if(ToolUtils.isListEmpty(appInfoList)){
                if(recyclerView != null){
                    recyclerView.refreshComplete();
                }

                return;
            }

            softWareAdapter.setAppInfoList(appInfoList);
            softWareAdapter.notifyDataSetChanged();
            if(recyclerView != null){
                recyclerView.refreshComplete();
            }
        }
    }

    private class SoftWareAdapter extends  RecyclerView.Adapter<SoftWareAdapter.ViewHolder>{

        private List<AppInfo> appInfoList;

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.soft_mg_list_item, null, false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(final SoftWareAdapter.ViewHolder holder, int position) {
            if(appInfoList != null){
                final AppInfo appInfo = appInfoList.get(position);

                Drawable logo = appInfo.getIcon();
                holder.imageView.setImageDrawable(logo);
                holder.textView.setText(appInfo.getLabel());
                holder.itemView.setTag(position);//给view设置tag以作为参数传递到监听回调方法中

                if(type == 1){
                    holder.whiteButton.setVisibility(View.VISIBLE);
                    holder.blackButton.setVisibility(View.VISIBLE);
                }else {
                    holder.whiteButton.setVisibility(View.VISIBLE);
                    holder.blackButton.setVisibility(View.GONE);

                    holder.whiteButton.setText("移除");
                    holder.whiteButton.setEnabled(true);
                    holder.whiteButton.setBackgroundResource(R.drawable.blue_solid_radius_45);
                    holder.whiteButton.setTextColor(getResources().getColor(R.color.white_text_color));
                }

                if(type == 1){
                    if(ControlUtil.containPackage(true,appInfo.getPackageName())){
                        holder.whiteButton.setText("已加入白名单");
                        holder.whiteButton.setTextColor(getResources().getColor(R.color.white_text_color));
                        holder.whiteButton.setEnabled(false);

                        holder.blackButton.setVisibility(View.GONE);
                    }else {
                        holder.whiteButton.setText("加入白名单");
                        holder.whiteButton.setTextColor(getResources().getColor(R.color.primary_green_color));
                        holder.whiteButton.setEnabled(true);
                    }
                }

                holder.whiteButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(type == 1){
                            if(ControlUtil.getWhiteCount(appInfoList) >= 6){
                                showToast("最多只能添加6个白名单");
                                return;
                            }
                            ControlUtil.addPackage(true,appInfo.getPackageName());
                            holder.whiteButton.setText("已加入白名单");
                            holder.whiteButton.setTextColor(getResources().getColor(R.color.white_text_color));
                            holder.whiteButton.setEnabled(false);

                            holder.blackButton.setVisibility(View.GONE);

                            SoftMgPagerAdapter.whiteSoftFragment.setLoaded(false);
                            UmengEventUtil.onEvent(BabyApplication.getInstance(),"soft_manager_click_id","addWhite");
                        }else if(type == 2){
                            ControlUtil.deletePackage(false,appInfo.getPackageName());

                            setAppInfoList(SystemUtils.getUsePackages(false,getActivity()));
                            notifyDataSetChanged();

                            SoftMgPagerAdapter.allSoftFragment.setLoaded(false);
                            UmengEventUtil.onEvent(BabyApplication.getInstance(),"soft_manager_click_id","deleteBlack");
                        }else if(type == 3){
                            ControlUtil.deletePackage(true,appInfo.getPackageName());
                            setAppInfoList(SystemUtils.getUsePackages(true,getActivity()));
                            notifyDataSetChanged();

                            SoftMgPagerAdapter.allSoftFragment.setLoaded(false);
                            UmengEventUtil.onEvent(BabyApplication.getInstance(),"soft_manager_click_id","deleteWhite");
                        }

                    }
                });

                if(type == 1){
                    if(ControlUtil.containPackage(false,appInfo.getPackageName())){
                        holder.blackButton.setText("已禁用");
                        holder.blackButton.setTextColor(getResources().getColor(R.color.white_text_color));
                        holder.blackButton.setEnabled(false);

                        holder.whiteButton.setVisibility(View.GONE);
                    }else {
                        holder.blackButton.setText("禁用");
                        holder.blackButton.setTextColor(getResources().getColor(R.color.primary_green_color));
                        holder.blackButton.setEnabled(true);
                    }
                }

                holder.blackButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ControlUtil.addPackage(false,appInfo.getPackageName());
                        holder.blackButton.setText("已禁用");
                        holder.blackButton.setEnabled(false);
                        holder.blackButton.setTextColor(getResources().getColor(R.color.white_text_color));

                        holder.whiteButton.setVisibility(View.GONE);

                        SoftMgPagerAdapter.blackSoftFragment.setLoaded(false);
                        UmengEventUtil.onEvent(BabyApplication.getInstance(),"soft_manager_click_id","addBlack");
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            if(appInfoList == null){
                return 0;
            }else{
                return appInfoList.size();
            }
        }

        class ViewHolder extends RecyclerView.ViewHolder{
            private ImageView imageView;
            private TextView textView;
            private Button whiteButton;
            private Button blackButton;

            public ViewHolder(View itemView) {
                super(itemView);

                imageView = itemView.findViewById(R.id.soft_mg_item_img);
                textView = itemView.findViewById(R.id.soft_mg_item_tv);
                whiteButton = itemView.findViewById(R.id.soft_mg_item_white_btn);
                blackButton = itemView.findViewById(R.id.soft_mg_item_black_btn);
            }
        }

        public List<AppInfo> getAppInfoList() {
            return appInfoList;
        }

        public void setAppInfoList(List<AppInfo> appInfoList) {
            this.appInfoList = appInfoList;
        }
    }

    public void sendMessage(){
        Message message = handler.obtainMessage();
        message.sendToTarget();
    }

    public boolean isLoaded() {
        return isLoaded;
    }

    public void setLoaded(boolean loaded) {
        isLoaded = loaded;
    }
}
